﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.IO;

namespace OperateCamera
{
    class HttpServer
    {

        static HttpListener sSocket = null;
        static string serverUrl = "";
        static string serverPort = "";
        static HttpListenerResponse response;

        public static void Listen()
        {

            sSocket = new HttpListener();
            sSocket.Prefixes.Add("http://*:80/");
            sSocket.Start();
            sSocket.BeginGetContext(new AsyncCallback(GetContextCallBack), sSocket);
            Console.Read();

        }


        static void GetContextCallBack(IAsyncResult ar)
        {
            try
            {
                sSocket = ar.AsyncState as HttpListener;
                HttpListenerContext context = sSocket.EndGetContext(ar);
                sSocket.BeginGetContext(new AsyncCallback(GetContextCallBack), sSocket);


                serverUrl = context.Request.Url.Host;
                serverPort = context.Request.Url.Port.ToString();


                if (context.Request.Url.PathAndQuery.IndexOf("startRec") != -1) {

                    string message = "已开始录像!";
                    byte[] byteMessage = Encoding.UTF8.GetBytes(message);
                    context.Response.OutputStream.Write(byteMessage, 0, byteMessage.Length);
                    context.Response.Close();

                }
                else if (context.Request.Url.PathAndQuery.IndexOf("stopRec") != -1)
                {

                    string message = "录像已停止!";
                    byte[] byteMessage = Encoding.UTF8.GetBytes(message);
                    context.Response.OutputStream.Write(byteMessage, 0, byteMessage.Length);
                    context.Response.Close();

                }
                else {

                    //判断请求类型
                    string html = GetHtml("index.html");

                    html = html.Replace("[Host]", serverUrl);
                    html = html.Replace("[Port]", serverPort);

                    byte[] bytes = System.Text.Encoding.Default.GetBytes(html);

                    context.Response.OutputStream.Write(bytes, 0, bytes.Length);

                    context.Response.Close();
                
                
                }

                

                //sSocket.EndGetContext(ar);
                //Console.WriteLine(context.Request.Url.PathAndQuery);
                //其它处理code  
                


                
                sSocket.EndGetContext(ar);
            }
            catch { }
        }



        //推送图片
        private static void pushImage(byte[] img, HttpListenerResponse rsp)
        {

            string rspheard = "--BoundaryString\r\nContent-type: image/jpg\r\nContent-Length: {0}\r\n\r\n";
            string strrn = "\r\n";

            rspheard = string.Format(rspheard, img.Length);

            byte[] heardbuff = Encoding.ASCII.GetBytes(rspheard);
            rsp.OutputStream.Write(heardbuff, 0, heardbuff.Length);
            rsp.OutputStream.Write(img, 0, img.Length);

        }


        //显示界面

        static string GUI()
        {

            string html = "<div>监控系统</div>";
            html += "<iframe src='http://" + serverUrl + ":" + serverPort + "/?action=getImage' style='width:100%;height:80%;background:black;margin-bottom:20px;'></iframe>";
            //html += "<iframe src='http://www.youku.com' style='width:100%;height:80%;background:black;margin-bottom:20px;'></iframe>";
            html += "<input type='button' value='开始录像' onclick='javascript:window.location.url=\'http://" + serverUrl + ":" + serverPort + "/?action=startRec\''/>   <input type='button' value='开始录像' onclick='javascript:window.location.url=\'http://" + serverUrl + ":" + serverPort + "/?action=stopRec\''/> ";

            return html;


        }

        //getHtml
        static string GetHtml( string fileName){
            
            string webPath = Environment.CurrentDirectory + "\\web" ;
            string filePath = webPath + "\\" + fileName;

            string _res = "";
            
            try
            {

                FileStream fs = File.Open(filePath, FileMode.Open);
                fs.Seek(0, SeekOrigin.Begin);
                byte[] data = new byte[fs.Length];

                fs.Read(data,0,(int)fs.Length);

                fs.Close();

                //_res = Encoding.Unicode.GetString(data);
                _res = Encoding.UTF8.GetString(data);

            }
            catch (Exception fileOpenException) {


                Console.WriteLine(fileOpenException.Message);
            }

            //Console.WriteLine("html === >" + _res);

            return _res; 

        }



        public static Byte[] ReadImageFile(string path)
        {
            FileStream fs = File.OpenRead(path); //OpenRead
            int filelength = 0;
            filelength = (int)fs.Length; //获得文件长度 
            Byte[] image = new Byte[filelength]; //建立一个字节数组 
            fs.Read(image, 0, filelength); //按字节流读取 
            fs.Close();

            return image;
        }





    }
}
